import logging
import os
import time
import requests
from logging.handlers import TimedRotatingFileHandler

LOG_FORMAT = "时间：%(asctime)s,级别：%(levelname)s,输出：%(message)s"
LOG_PATH = os.path.join(os.path.dirname(__file__), "../logs")
LOG_LEVEL = logging.INFO


def get_logger(name, level=None):
    logger = logging.getLogger(name)
    if len(logger.handlers) == 2:
        return logger
    logger_file = os.path.join(LOG_PATH, "{0}.log".format(name))
    if not os.path.exists(LOG_PATH):
        os.mkdir(LOG_PATH)
    logging_format = logging.Formatter(LOG_FORMAT)

    logger_level = level or LOG_LEVEL

    file_handler = TimedRotatingFileHandler(logger_file, when="D", backupCount=30)
    file_handler.setLevel(logger_level)
    file_handler.setFormatter(logging_format)

    console_handler = logging.StreamHandler()
    console_handler.setLevel(logger_level)
    console_handler.setFormatter(logging_format)

    logger.addHandler(file_handler)
    logger.addHandler(console_handler)
    logger.setLevel(logger_level)
    return logger


def phone_check(s):
    phone_prefix = ['130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '150', '151', '152', '153',
                    '156', '158', '159', '170', '183', '182', '185', '186', '187', '188', '189']
    # 检测号码是否长度是否合法。
    if len(s) != 11:
        return False
    else:
        if s.isdigit():
            if s[:3] in phone_prefix:
                return True
            else:
                return False
        else:
            return False


def check_id_data(n):  # 检查数据
    if len(str(n)) != 18:
        return False
    factor = (7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2)
    last = ("1", "O", "X", "9", "8", "7", "6", "5", "4", "3", "2")
    n = str(n)
    sum = 0
    if int(n[16]) % 2 == 0:  # 判断第17位是否为偶数
        gender = "女"
    else:
        gender = "男"
    for i in range(0, 17):
        sum += int(n[i]) * factor[i]  # 求前17位与加权数相乘的和
    sum %= 11  # 取余,计算余数对应的第18位身份证号
    if (last[sum]) == str(n[17]):  # 第18位相同
        # print("身份证号规则校验通过,校验码是:"+str(last[sum])+",该身份证号使用者为"+str(gender)+"性")
        return True
    else:
        # print("当前身份证号校验失败,校验码应为:"+str(last[sum])+",当前校验码是:"+str(n[17]))
        return False


def get_time_str(timestamp):
    try:
        time_array = time.localtime(timestamp)
        res = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
    except:
        res = '0000-00-00 00:00:00'
    return res


def get_timestamp(time_str):
    try:
        res = int(time.mktime(time.strptime(time_str, '%Y-%m-%d %H:%M:%S')))
    except:
        res = 0
    return res


def test_ip_proxy(ip, timeout):
    proxies = {'http': 'http://' + ip, 'https': 'http://' + ip}
    try:
        r = requests.get('https://m.o2o.yesmywine.com/1member1bb', proxies=proxies, timeout=timeout)
        return 1
    except:
        return 0
